package foundation.common.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

/**
 * Application class is responsible for the services startup and configuration
 * and service retrieval as well acting as service locator for Tecso
 * applications. <br>
 * 
 * @author frepond
 * 
 */

public class Application implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	// Default spring configuration lookup
	private static String BEANS_PATH = "classpath*:META-INF/*service.beans.xml";

	/**
	 * Starts up the application registering beans in the classpath.
	 */
	public static void startup() {
		if (applicationContext == null)
			registerServices();
	}

	public static void startup(String beansPath) {
		BEANS_PATH = beansPath;
		if (applicationContext == null)
			registerServices();
	}

	/**
	 * Shuts down the application.
	 */
	public static void shutdown() {
		// TODO nothing to do yet (?)
	}

	private static void registerServices() {
		// load resources ending with ".beans" in classpath META-INF folders
		applicationContext = new ClassPathXmlApplicationContext(BEANS_PATH);
	}

	/**
	 * Returns the bean whose id matches the given name.
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		if (applicationContext == null)
			registerServices();

		return applicationContext.getBean(name);
	}

	protected ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public void setApplicationContext(ApplicationContext context) {
		applicationContext = context;
	}
}